<?php

class ZFBootstrap_Grid_Formatter_Btcolumn implements Bvb_Grid_Formatter_FormatterInterface {

	protected $_options = array('border' => 0);

	public function __construct($options = array()) {
		$this->_options = $options;

		return;
	}

	private function _formatBt($bt) {
		if ($bt['type'] == 'bootstrap-icon-edit') {
			$bt['type'] = 'bootstrap-icon';
			$bt['icon'] = 'pencil';
		}
		if ($bt['type'] == 'bootstrap-icon-del') {
			$bt['type'] = 'bootstrap-icon';
			$bt['icon'] = 'trash';
		}
		if ($bt['type'] == 'bootstrap-icon-zoom') {
			$bt['type'] = 'bootstrap-icon';
			$bt['icon'] = 'zoom-in';
		}

		$exibe = true;
		if (isset($bt['conditions'])) {
			foreach ($bt['conditions'] as $condition) {
				$exibe = false;
				foreach ($condition['expression'] as $expression) {
					switch ($expression['operator']) {
						case '!=':
							$exibe = ($expression['field'] != $expression['value']);
							break;
						case '>':
							$exibe = ($expression['field'] > $expression['value']);
							break;
						case '<':
							$exibe = ($expression['field'] < $expression['value']);
							break;
						default:
							$exibe = ($expression['field'] == $expression['value']);
					}
					
					if($exibe) {
						break;
					}
				}
				
				if( ($exibe) and (isset($condition['tochange'])) ) {
					$bt = array_merge($bt, $condition['tochange']);
				}
			}
		}

		switch ($bt['type']) {
			case 'bootstrap-icon':
				$exibe = $this->_formatBtImgLink($bt);
				break;
			default:
				$exibe = '';
		}
		return $exibe;
	}

	private function _formatBtImgLink($bt) {
		if(!isset($bt['class'])) {
			$bt['class'] = 'btn btn-mini';
		}

		return strtr('<a href="[url]" title="[desc]" class="[class]"><i class="icon-[icon]"></i></a>', array(
					'[desc]' => isset($bt['title']) ? $bt['title'] : ucfirst($bt['btname']),
					'[icon]' => $bt['icon'],
					'[url]' => $bt['url'],
					'[class]' => $bt['class'],
				));
	}

	public function format($value) {

		$r = array();
		foreach ($this->_options['bt'] as $btName => $bt) {
			$bt['btname'] = $btName;
			$r[] = $this->_formatBt($bt);
		}

		return join('', $r);
	}

}